package com.nidu.demo.notify.ability;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.notify.gateway.NotifyTemplateGateway;
import com.nidu.demo.notify.model.NotifyTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RequiredArgsConstructor
public class NotifyTemplateDomainService {


    private final NotifyTemplateGateway gateway;

    public NotifyTemplate validateNotifyTemplate(String code){
        NotifyTemplate template = gateway.getByCode(code);
        if (template == null) {
            throw new BizException(ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_NOT_FOUND.getCode(),
                    ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_NOT_FOUND.getMessage());
        }
        template.isDeleted();
        return template;
    }

    public void validateTemplateParams(NotifyTemplate template, Map<String, Object> templateParams) {
        template.getTemplateParams().forEach(key -> {
            Object value = templateParams.get(key);
            if (value == null) {
                throw new BizException(ErrorCodeConstants.NOTIFY_TEMPLATE_PARAM_MISS.getCode(), ErrorCodeConstants.NOTIFY_TEMPLATE_PARAM_MISS.getMessage());
            }
        });
    }

    /**
     * 检查部门编码是否重复
     * @param code 部门编码
     * @param exculdeId 排除的Id
     */
    public void validateDuplicate(String code, Long exculdeId) {
        NotifyTemplate notifyTemplate = gateway.getByCode(code);
        if(notifyTemplate != null){
            if(exculdeId == null){
                throw new BizException(ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_DUPLICATE.getMessage());
            }
            if (!exculdeId.equals(notifyTemplate.getId())) {
                throw new BizException(ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.NOTIFY_TEMPLATE_CODE_DUPLICATE.getMessage());
            }
        }
    }

}